<template>
  <div>
    <top-list :activeIndex="3+''"></top-list>
    <div>
      <el-button plain type="primary" @click="testeeEdit(0)" :disabled="!isSiteRole" style="margin-left: 20px;margin-top: 20px;margin-bottom: 20px">添加受试者</el-button>
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="searchSubject()">
        <el-form-item>
          <el-select v-model="v_result" placeholder="请选择采集阶段" style="margin-left: 20px;width:200rem;" @change="currStationChange">
            <el-option
              v-for="item in v_data"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input style="width:200rem;" v-model="dataForm.testeeNo" placeholder="编号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input style="width:200rem;" v-model="dataForm.name" placeholder="姓名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-select style="width:200rem;" v-model="dataForm.sex" clearable placeholder="性别">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="0"></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item>-->
<!--          <el-input style="width:200rem;" v-model="dataForm.birthday" placeholder="出生日期" clearable></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-input v-model="dataForm.subject_appointment" placeholder="预约时间" clearable></el-input>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button @click="searchSubject()">查询</el-button>
        </el-form-item>
      </el-form>

    </div>
    <el-table
      :data="dataList"
      :key="itemKey"
      border
      stripe
      v-loading="dataListLoading"
      style="width: 100%;">
      <el-table-column prop="testeeNo" header-align="center" align="center" label="受试者编号"></el-table-column>
      <el-table-column prop="name" header-align="center" align="center" label="姓名"></el-table-column>
      <el-table-column prop="sex" header-align="center" align="center" label="性别"></el-table-column>
      <el-table-column prop="birthday" header-align="center" align="center" label="出生日期"></el-table-column>
      <el-table-column prop="siteCode" header-align="center" align="center" label="分中心编码"></el-table-column>
      <el-table-column prop="achievingRate" header-align="center" align="center" label="完成率"></el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="lookHandle(scope.row.id)">查看</el-button>
          <el-button type="text" size="small" @click="testeeEdit(scope.row.id)">编辑</el-button>
          <el-button type="text" size="small" @click="testeeDelete(scope.row.id,scope.row.name)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
    <testee-update v-if="updateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></testee-update>
  </div>
</template>

<script>
import subject from '@/api/subject'
import myUtils from '../../api/myUtils'
import research from '@/api/research'
import TopList from '@/components/TopList'
import testeeUpdate from './testee-update.vue'
import site from '../../api/site'
export default {
  components:{
    testeeUpdate,
    TopList
  },
  data() {
    return {
      dataList: [
      ],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataForm: {},
      activeIndex: '3',
      v_data: [{"name":"基线","code":"v1","order":1},{"name":"1年随访","code":"v2","order":2}],
      v_result: '',
      itemKey: '',
      updateVisible: false,
      isSiteRole: false
    }
  },
  created() {
    this.getVCode();
    let role = myUtils.getRole(this.$route.query.subjectPkId,this.$store.getters.roles,this.$store.getters.isSystemAdministrator);
    if( role == 4 || role == 5 || role == 6 || role == 7)
    {
      this.isSiteRole = true;
    }
    console.log(this.dataForm)
    let width = document.body.clientWidth;
    // console.log(width)
    let fontsize = (width / 2203)
    document.documentElement.style.fontSize = fontsize + "px"
  },
  methods: {
    testeeEdit(id)
    {
      console.log(id)
      let subjectPkId = this.$route.query.subjectPkId
      let role = myUtils.getRole(subjectPkId,this.$store.getters.roles,this.$store.getters.isSystemAdministrator);
      if(role !== 4 && role !== 5 && role !== 6 && role !== 7) //采集和队列管理员无权
      {
        this.$message.error("您不是分中心管理员");
        return;
      }
      this.updateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
      console.log(this.updateVisible)
    },

    currStationChange()
    {
      // console.log("调用了")
      for(let i=0;i<this.dataList.length;i++)
      {
        try{
          let fobject = JSON.parse(this.dataList[i].finishJson)
          // console.log(fobject[this.v_result])
          // console.log("++++++++++++++++++++++++++++++++++++")
          if(fobject[this.v_result]== undefined)
          {
            this.dataList[i].achievingRate = this.toPercent(0);
          }
          else {
            this.dataList[i].achievingRate = this.toPercent(fobject[this.v_result])
          }
        }
        catch (err)
        {
          this.dataList[i].achievingRate = 0;
        }
      }
      this.itemKey = Math.random()
    },

    handleSelect(key, keyPath) {
      if(key==='0')
      {
        this.$router.push({path:`/upload/file-list?subjectPkId=${this.$route.query.subjectPkId}`})
      }
      if(key==='1')
      {
        // this.$router.push(0)
        this.$router.push({path:`/upload/research-manager?subjectPkId=${this.$route.query.subjectPkId}`})
      }
      else if(key==='2')
      {
        this.$router.push({path:`/upload/task?subjectPkId=${this.$route.query.subjectPkId}`})
      }
      else if(key==='3')
      {
        this.$router.push({path:`/upload/subject-manager?subjectPkId=${this.$route.query.subjectPkId}`})
      }
      else if(key==='4')
      {
        this.$router.push({path:`/upload/device?subjectPkId=${this.$route.query.subjectPkId}`})
      }
    },

    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },

    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },

    toPercent(point){
      var percent = Number(point*100).toFixed(1);
      percent += "%";
      return percent;
    },

    getDataList()
    {
      let role = myUtils.getRole(this.$route.query.subjectPkId,this.$store.getters.roles,this.$store.getters.isSystemAdministrator)
      if(role==1||role==4||role==5)
      {
        this.dataForm['sitePkId'] = myUtils.getSite(this.$route.query.subjectPkId,this.$store.getters.roles);
      }

      this.dataForm['subjectPkId'] = this.$route.query.subjectPkId
      this.dataForm.pageNum = this.pageIndex;
      this.dataForm.pageSize = this.pageSize;
      //    pageNum:pageIndex,
      //pageSize:pageSize,
      //
      subject.testeeSearch1(this.dataForm).then((response)=>{
        this.dataList = response.data.records;
        this.totalPage = response.data.total;
        for(let i=0;i<this.dataList.length;i++)
        {

          if(this.dataList[i].sex==1)
          {
            this.dataList[i].sex='男'
          }
          else {
            this.dataList[i].sex='女'
          }

          this.dataList[i].birthday = this.dataList[i].birthday.split(" ")[0]

          try{
            let fobject = JSON.parse(this.dataList[i].finishJson)
            // console.log(fobject[this.v_result])
            // console.log("++++++++++++++++++++++++++++++++++++")
            if(fobject[this.v_result]== undefined)
            {
              this.dataList[i].achievingRate = this.toPercent(0);
            }
            else {
              this.dataList[i].achievingRate = this.toPercent(fobject[this.v_result])
            }
          }
          catch (err)
          {
            this.dataList[i].achievingRate = 0;
          }
        }
      })
      // this.dataListLoading = true;
      //
      //
      // //@这里可以加个条件，如果是队列管理员的话 就不用加入site这个条件的
      // //this.$route.query
      // subject.testeeSearch(this.$route.query.subjectPkId,this.$store.getters.site,this.pageIndex,this.pageSize).then((response)=>{
      //   this.dataList = response.data.records;
      //   this.totalPage = response.data.total;
      //   for(let i=0;i<this.dataList.length;i++)
      //   {
      //     if(this.dataList[i].sex==1)
      //     {
      //       this.dataList[i].sex='男'
      //     }
      //     else {
      //
      //       this.dataList[i].sex='女'
      //     }
      //
      //   }
      // })
      //
      //
      //
      //
      // this.dataListLoading = false;
      // //this.totalPage = this.dataList.length;
    },

    searchSubject()
    {
      let role = myUtils.getRole(this.$route.query.subjectPkId,this.$store.getters.roles,this.$store.getters.isSystemAdministrator)
      if(role==1||role==3||role==4||role==5||role==6||role==7)  //采集用户和中心管理员要有加入中心的筛选条件
      {
        this.dataForm['sitePkId'] = myUtils.getSite(this.$route.query.subjectPkId,this.$store.getters.roles);
      }
      this.dataForm['subjectPkId'] = this.$route.query.subjectPkId
      this.dataForm.pageNum = 1;
      this.dataForm.pageSize = this.pageSize;
      if(this.dataForm.testeeNo === "") this.dataForm.testeeNo = null;
      if(this.dataForm.name === "") this.dataForm.name = null;
      //    pageNum:pageIndex,
      //pageSize:pageSize,
      //
      subject.testeeSearch1(this.dataForm).then((response)=>{
        this.dataList = response.data.records;
        this.totalPage = response.data.total;
        for(let i=0;i<this.dataList.length;i++)
        {
          if(this.dataList[i].sex==1)
          {
            this.dataList[i].sex='男'
          }
          else {
            this.dataList[i].sex='女'
          }

          this.dataList[i].birthday = this.dataList[i].birthday.split(" ")[0]

          try{
            let fobject = JSON.parse(this.dataList[i].finishJson)
            // console.log(fobject[this.v_result])
            // console.log("++++++++++++++++++++++++++++++++++++")
            if(fobject[this.v_result]== undefined)
            {
              this.dataList[i].achievingRate = this.toPercent(0);
            }
            else {
              this.dataList[i].achievingRate = this.toPercent(fobject[this.v_result])
            }
          }
          catch (err)
          {
            this.dataList[i].achievingRate = 0;
          }

        }
      })
      //this.dataForm={}//@ 现在的逻辑是查询完之后自己把 这个form变成空的
    },
    lookHandle(testeeNo)
    {
      this.$router.push({path:`/upload/upload?testeeNo=${testeeNo}&subjectPkId=${this.$route.query.subjectPkId}`})
    },

    getVCode()
    {
      research.getBysubjectPkId(this.$route.query.subjectPkId).then((response) => {
        let data = response.data;

        this.v_data = eval(data.vpInfo);//json String格式转成数组对象

        if(this.v_data.length>=1)
        {
          this.v_result = this.v_data[0].code;
        }
        this.getDataList();
      })
    },

    testeeDelete(id,name){
      let role =myUtils.getRole(this.$route.query.subjectPkId,this.$store.getters.roles,this.$store.getters.isSystemAdministrator);
      if(role !== 4 && role !== 5 && role !== 6 && role !== 7) //采集和队列管理员无权
      {
        this.$message.error("您不是分中心管理员");
        return;
      }
      this.$confirm(
        `确定对[受试者：${name}]进行删除操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(()=>{
        subject.deleteTestee(id).then(( response ) => {
          console.log(response)
          if (response.code  === '000000') {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 700,
              onClose: () => {
                this.getDataList()
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      })
    }
  },
}
</script>
<style>


</style>
